//
//  WCSinaLoginWindowController.m
//  WeboCon
//
//  Created by black sun on 12-3-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "WCSinaLoginWindowController.h"
#import "NSString+YHTTPURLString.h"


@interface WCSinaLoginWindowController ()

@end

@implementation WCSinaLoginWindowController
@synthesize webView;


- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
    }
    return self;
}

- (void)windowDidLoad
{
    NSString *url = [@"https://api.weibo.com/oauth2/authorize" requestAuthorizationCodeUrlStringByAddingClientId:APP_KEY
                                                                                redirectURI:Redirect_URL
                                                                                scope:nil
                                                                                state:nil];
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    self.webView.frameLoadDelegate = self;
    [[self.webView mainFrame] loadRequest:request];
    
    [super windowDidLoad];
}
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame{
    //NSLog(@"didStartProvisionalLoadForFrame:%@",[sender mainFrameURL]);
}
- (void)webView:(WebView *)sender willPerformClientRedirectToURL:(NSURL *)URL delay:(NSTimeInterval)seconds fireDate:(NSDate *)date forFrame:(WebFrame *)frame{
    //NSLog(@"%@",[URL description]);
}
- (void)webView:(WebView *)sender didReceiveServerRedirectForProvisionalLoadForFrame:(WebFrame *)frame{
    //NSLog(@"URL=%@",[sender mainFrameURL]);
    NSString *url = [sender mainFrameURL];
    NSDictionary *p = [url queryParameters];
    NSError * error = [NSError errorByCheckingOAuthv2RedirectURIParameters:p];
    if (nil == error) {
        NSString * authorizationCode = [p objectForKey:YOAuthv2AuthorizationCode];
        if (authorizationCode) {
            
            NSDictionary * parameters = YOAuthv2GetAccessTokenRequestParametersForAuthorizationCode(authorizationCode,
                                                                                                    Redirect_URL);
            NSMutableDictionary * addParams = [NSMutableDictionary dictionaryWithDictionary:parameters];
            [addParams setObject:APP_KEY forKey:YOAuthv2ClientId];
            [addParams setObject:APP_SECRET forKey:YOAuthv2ClientSecret];
            
            NSString * urlString = [@"https://api.weibo.com/oauth2/access_token" URLStringByAddingParameters:addParams];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
            request.delegate = self;
            [request setRequestMethod:@"POST"];
            [request startAsynchronous];
        }
        else {
            /*UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"ytoolkit"
                                                                 message:@"Not denied and not authorized? I'm confused"
                                                                delegate:nil
                                                       cancelButtonTitle:@"Anyway"
                                                       otherButtonTitles:nil];
            [alertView show];
            YRELEASE_SAFELY(alertView);*/
        }
    }
    
}

#pragma mark - Network
- (void)requestFinished:(ASIHTTPRequest *)request 
{
    
    NSDictionary * parameters = [request.responseString JSONValue];
    NSLog(@"response:%@", request.responseString);
    WCUserContext *userContext = [WCUserContext sharedInstance];
    [userContext saveOldUserData];
    
    userContext.accessToken = [parameters objectForKey:YOAuthv2AccessToken];
    userContext.refreshtoken = [parameters objectForKey:YOAuthv2RefreshToken];
    id value = [parameters objectForKey:YOAuthv2ExpiresIn];
    if (IS_INSTANCE_OF(value, NSNumber)) {
        userContext.expiresin = value;
    }else if (IS_INSTANCE_OF(value, NSString)) {
        NSUInteger v = [value integerValue];
        userContext.expiresin = [NSNumber numberWithInteger:v];
    }
    id uid = [parameters objectForKey:OAuthUserIdKey];
    if (IS_INSTANCE_OF(uid, NSNumber)) {
        userContext.currentUserId = value;
    }else if (IS_INSTANCE_OF(uid, NSString)) {
        NSUInteger u = [uid integerValue];
        userContext.currentUserId = [NSNumber numberWithInteger:u];
    }
    
    //发出新用户登录成功的通知。
    [[NSNotificationCenter defaultCenter] postNotificationName:NewUserLoginSuccessNotification object:nil userInfo:[NSDictionary dictionaryWithObject:userContext.currentUserId forKey:OAuthUserIdKey]];
    
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"error: %@",[request.error localizedDescription]);
}

@end
